package com.ddone.finance.controller.api;


import com.alibaba.fastjson.JSON;
import com.ddone.base.util.JwtUtils;
import com.ddone.common.result.Response;
import com.ddone.finance.hfb.RequestHelper;
import com.ddone.finance.pojo.vo.UserBindVo;
import com.ddone.finance.service.UserBindService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 前端控制器
 * </p>
 *
 * @author ddone
 * @since 2024-04-10
 */
@Api(tags = "会员账号绑定模块")
@RestController
@RequestMapping("/core/api/userBind")
@Slf4j
public class UserBindController {

    @Resource
    private UserBindService userBindService;

    @ApiOperation("账户绑定提交数据")
    @PostMapping("/bind")
    public Response<Object> bind(
            @ApiParam("用户绑定对象")
            @Valid
            @RequestBody UserBindVo userBindVo,
            @RequestHeader("token") String token) {
        Long userId = JwtUtils.getUserId(token);
        String formStr = userBindService.commitBindUser(userBindVo, userId);
        return Response.ok(formStr);
    }

    @ApiOperation("账户绑定异步回调")
    @PostMapping("/notify")
    public String notify(HttpServletRequest request) {
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
        log.info("用户账号绑定异步回调：" + JSON.toJSONString(paramMap));

        //校验签名
        if(!RequestHelper.isSignEquals(paramMap)) {
            log.error("用户账号绑定异步回调签名错误：" + JSON.toJSONString(paramMap));
            return "fail";
        }

        //修改绑定状态
        userBindService.notify(paramMap);
        return "success";
    }
}

